//
//  SelectionScrollView.m
//  TabulaImaginarius4
//
//  Created by TA2 on 6/6/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SelectionScrollView.h"
#import "BackgroundProtocol.h"

@implementation SelectionScrollView

@synthesize zoomGesture;
@synthesize tileSize;
@synthesize tokenImageViews;
@synthesize backgroundImageViews;
@synthesize mainBackgroundViews;
@synthesize objectImageViews;
@synthesize changeMainBackgroundsMode;
@synthesize snapColorViews;
@synthesize colorViews;
@synthesize contentView;
@synthesize currentImageViews;


- (void)dealloc {
    [zoomGesture release];
    zoomGesture = nil;
	[timer release];
    timer = nil;
    [selectionAnimation release];
    selectionAnimation = nil;
	[tokenImageViews release];
    tokenImageViews = nil;
    [objectImageViews release];
    objectImageViews = nil;
	[backgroundImageViews release];
    backgroundImageViews = nil;
	[mainBackgroundViews release];
    mainBackgroundViews = nil;
    [colorViews release];
    colorViews = nil;
    [snapColorViews release];
    snapColorViews = nil;
	[contentView release];
    contentView = nil;
    [eraserButton release];
    eraserButton = nil;
    [super dealloc];
}

- (void)awakeFromNib {
	self.delegate = self;
	self.showsVerticalScrollIndicator = NO;
	self.showsHorizontalScrollIndicator = NO;
	self.bounces = YES;
	self.bouncesZoom = YES;
	self.decelerationRate = UIScrollViewDecelerationRateFast;
	self.scrollEnabled = NO;
	self.multipleTouchEnabled = NO;
	self.autoresizesSubviews = YES;
    
    changeMainBackgroundsMode = NO;
    
	lastSelectedTokenView = nil;
    lastSelectedObjectView = nil;
	lastSelectedBackgroundView = nil;
    lastSnapColorView = nil;
    lastColorView = nil;
    
	selectionAnimation = [[CABasicAnimation animationWithKeyPath:@"transform"] retain];
	selectionAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
	selectionAnimation.duration = 0.25;
	selectionAnimation.repeatCount = HUGE_VALF;
	selectionAnimation.autoreverses = YES;
	selectionAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 0.5)];
    
	tokenImageViews = [[NSMutableArray alloc] init];
	backgroundImageViews = [[NSMutableArray alloc] init];
	mainBackgroundViews = [[NSMutableArray alloc] init];
    objectImageViews = [[NSMutableArray alloc] init];
    colorViews = [[NSMutableArray alloc] init];
    snapColorViews = [[NSMutableArray alloc] init];
	[self makeTokenSelectArray];
	[self makeBackgroundSelectArray];
	[self makeAllBackgroundSelectArray];
    [self makeObjectSelectArray];
    [self makeColorSelectArray];
    [self makeSnapColorSelectArray];

    [LoadedImages sharedLoadedImages].eraserActivated = NO;
    [LoadedImages sharedLoadedImages].selectedColor = [UIColor blackColor];
    [LoadedImages sharedLoadedImages].drawingWidth = 2.0;
    if (eraserButton.alpha == 1.0) {
        [self fade:eraserButton fromValue:1.0 toValue:0.4 withDuration:0.25];
    } 
    
    SelectionImageView *selectedImageView2;
    [self setUpSelectionScroller:colorViews];
    selectedImageView2 = ((SelectionImageView *)([self.subviews objectAtIndex:0]));
    [selectedImageView2.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
    lastColorView = selectedImageView2;
}

- (CGPoint)maximumContentOffset {
    return CGPointMake(self.contentSize.width - self.bounds.size.width, self.contentSize.height - self.bounds.size.height);
}

- (CGPoint)minimumContentOffset {
    return CGPointZero;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
	return nil;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //mode-switching version
    /*if (self.alpha == 1.0) {
        UITouch *touch = [touches anyObject];
        currentPoint = [touch locationInView:self];
        if (!timer) {
            timer = [NSTimer scheduledTimerWithTimeInterval: 0.2
                                                     target: self
                                                   selector: @selector(selectIcon)
                                                   userInfo: nil
                                                    repeats: NO];
        }
    } else {
        [LoadedImages sharedLoadedImages].eraserActivated = NO;
        [self fade:self fromValue:self.alpha toValue:1.0 withDuration:0.25];
        [self fade:eraserButton fromValue:1.0 toValue:0.4 withDuration:0.25];
        [LoadedImages sharedLoadedImages].eraserActivated = NO;
		[LoadedImages sharedLoadedImages].selectedColor = [UIColor blackColor];
        [LoadedImages sharedLoadedImages].drawingWidth = 2.0;
    }*/
    if (self.alpha != 1.0) {
        [LoadedImages sharedLoadedImages].eraserActivated = NO;
        [self fade:self fromValue:self.alpha toValue:1.0 withDuration:0.25];
        [self fade:eraserButton fromValue:1.0 toValue:0.4 withDuration:0.25];
        [LoadedImages sharedLoadedImages].selectedColor = [LoadedImages sharedLoadedImages].selectedSavedColor;
        [LoadedImages sharedLoadedImages].drawingWidth = 2.0;
    }
    UITouch *touch = [touches anyObject];
    currentPoint = [touch locationInView:self];
    if (!timer) {
        timer = [NSTimer scheduledTimerWithTimeInterval: 0.2
                                                 target: self
                                               selector: @selector(selectIcon)
                                               userInfo: nil
                                                repeats: NO];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	if (self.contentSize.width > self.bounds.size.width) {
		UITouch *touch = [touches anyObject];
		CGPoint oldPoint = [touch previousLocationInView:self];
		CGPoint newPoint = [touch locationInView:self];
		CGPoint offset = self.contentOffset;
		offset.x += ((oldPoint.x - newPoint.x)); 
		if (offset.x < [self minimumContentOffset].x) {
			offset.x = [self minimumContentOffset].x;
		} else if (offset.x > [self maximumContentOffset].x) {
			offset.x = [self maximumContentOffset].x;
		}
		[self setContentOffset:offset animated:NO];
	}
	if (timer) {
		[timer invalidate];
		timer = nil;
	}
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	
}


- (void)selectIcon {
	if (currentImageViews == tokenImageViews && lastSelectedTokenView) {
		[lastSelectedTokenView.layer removeAnimationForKey:@"selectionAnimation"];
		[LoadedImages sharedLoadedImages].selectedTokenImage = nil;
	} else if (currentImageViews == backgroundImageViews && lastSelectedBackgroundView) {
		[lastSelectedBackgroundView.layer removeAnimationForKey:@"selectionAnimation"];
		[LoadedImages sharedLoadedImages].selectedBackgroundImage = nil;
	} else if (currentImageViews == mainBackgroundViews && lastSelectedMainBackgroundView) {
		[lastSelectedMainBackgroundView.layer removeAnimationForKey:@"selectionAnimation"];
		[LoadedImages sharedLoadedImages].selectedMainBackgroundImage = nil;
		if (changeMainBackgroundsMode) {
			contentView.backgroundView.map.backgroundImage = nil;
			[contentView.backgroundView.map clearLoadedBackgroundImage];
			[contentView.backgroundView setNeedsDisplay];
		}
	} else if (currentImageViews == objectImageViews && lastSelectedObjectView) {
        [lastSelectedObjectView.layer removeAnimationForKey:@"selectionAnimation"];
		[LoadedImages sharedLoadedImages].selectedObjectImage = nil;
    } else if (currentImageViews == colorViews && lastColorView) {
        [lastColorView.layer removeAnimationForKey:@"selectionAnimation"];
    } else if (currentImageViews == snapColorViews && lastSnapColorView) {
        [lastSnapColorView.layer removeAnimationForKey:@"selectionAnimation"];
		[LoadedImages sharedLoadedImages].selectedSnapColor = nil;
    } 
	int index = (int)(currentPoint.x / tileSize.width);
	if (index >= 0 && index < [self.subviews count]) {
		SelectionImageView *selectedImageView = ((SelectionImageView *)[self.subviews objectAtIndex:index]);
		if (currentImageViews == tokenImageViews) {
            [LoadedImages sharedLoadedImages].selectedTokenImage = selectedImageView.imagePath;
            [selectedImageView.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
            lastSelectedTokenView = selectedImageView;
		} else if (currentImageViews == backgroundImageViews) {
            [LoadedImages sharedLoadedImages].selectedBackgroundImage = selectedImageView.imagePath;
            [selectedImageView.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
            lastSelectedBackgroundView = selectedImageView;
		} else if (currentImageViews == mainBackgroundViews && changeMainBackgroundsMode) {
            [LoadedImages sharedLoadedImages].selectedMainBackgroundImage = selectedImageView.imagePath;
            [selectedImageView.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
            lastSelectedMainBackgroundView = selectedImageView;
            contentView.backgroundView.map.backgroundImage = [[[LoadedImages sharedLoadedImages].selectedMainBackgroundImage lastPathComponent] stringByDeletingPathExtension];
            [(BackgroundProtocol *)[[NetworkController sharedNetworkController].networkProtocols objectForKey:([NSString stringWithString:@"BGP"])] sendMainBackground:contentView.backgroundView.map.backgroundImage];
            [contentView.backgroundView.map clearLoadedBackgroundImage];
            [contentView.backgroundView setNeedsDisplay];
		} else if (currentImageViews == objectImageViews) {
            [LoadedImages sharedLoadedImages].selectedObjectImage = selectedImageView.imagePath;
            [selectedImageView.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
            lastSelectedObjectView = selectedImageView;
        } else if (currentImageViews == colorViews) {
            [selectedImageView.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
            lastColorView = selectedImageView;
            [LoadedImages sharedLoadedImages].selectedColor = selectedImageView.backgroundColor;
        }  else if (currentImageViews == snapColorViews) {
            [LoadedImages sharedLoadedImages].selectedSnapColor = selectedImageView.imagePath;
            [selectedImageView.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
            lastSnapColorView = selectedImageView;
		} 
		
	}
	[timer invalidate];
	timer = nil;
}

- (void)selectMainBackgroundIcon:(NSString *)path {
    if (lastSelectedMainBackgroundView) {
        [lastSelectedMainBackgroundView.layer removeAnimationForKey:@"selectionAnimation"];
    }
    [LoadedImages sharedLoadedImages].selectedMainBackgroundImage = path;
    if (path) {
        for (SelectionImageView *selectView in mainBackgroundViews) {
            if ([[[selectView.imagePath lastPathComponent] stringByDeletingPathExtension] isEqualToString:path]) {
                [selectView.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
                lastSelectedMainBackgroundView = selectView;
            }
        }
    }
}

- (void)makeTokenSelectArray {
	NSArray *fileNames = [[NSBundle mainBundle] pathsForResourcesOfType:nil inDirectory:nil];
	[tokenImageViews removeAllObjects];
	CGSize thumbSize = (CGSize){75.0f, 75.0f};
	CGFloat x = 10.0f, y = 10.0f;
	for (NSString *fileName in fileNames) {
		if ([[fileName lastPathComponent]hasPrefix:@"token_"]) {
			SelectionImageView *imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
			UIImage *image = [UIImage imageWithContentsOfFile:fileName];
			imageView.image = image;
			imageView.imagePath = fileName;
			[[LoadedImages sharedLoadedImages].images setObject:image forKey:fileName];
			x += thumbSize.width + 5;
			[tokenImageViews addObject:imageView];
		}
	}
}

- (void)makeSnapColorSelectArray {
	NSArray *fileNames = [[NSBundle mainBundle] pathsForResourcesOfType:nil inDirectory:nil];
	[snapColorViews removeAllObjects];
	CGSize thumbSize = (CGSize){75.0f, 75.0f};
	CGFloat x = 10.0f, y = 10.0f;
	for (NSString *fileName in fileNames) {
		if ([[fileName lastPathComponent]hasPrefix:@"background_"]) {
			SelectionImageView *imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
			UIImage *image = [UIImage imageWithContentsOfFile:fileName];
			imageView.image = image;
			imageView.imagePath = fileName;
			[[LoadedImages sharedLoadedImages].images setObject:image forKey:fileName];
			x += thumbSize.width + 5;
			[snapColorViews addObject:imageView];
		}
	}
    for (SelectionImageView *imageView in snapColorViews) {
        [imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
        [imageView.layer setBorderWidth: 2.0];
    }
}
- (void)makeColorSelectArray {
	[colorViews removeAllObjects];
	CGSize thumbSize = (CGSize){75.0f, 75.0f};
	CGFloat x = 10.0f, y = 10.0f;
    
    SelectionImageView *imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor blackColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor redColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor blueColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor purpleColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor darkGrayColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor lightGrayColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor whiteColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor grayColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor greenColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor cyanColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor yellowColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor magentaColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor orangeColor];
    x += thumbSize.width + 5;
    [colorViews addObject:imageView];
    [imageView release];
    
    imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
    imageView.backgroundColor = [UIColor brownColor];
    [colorViews addObject:imageView];
    [imageView release];
    
    for (SelectionImageView *imageView in colorViews) {
        [imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
        [imageView.layer setBorderWidth: 2.0];
    }
}

- (void)makeObjectSelectArray {
	NSArray *fileNames = [[NSBundle mainBundle] pathsForResourcesOfType:nil inDirectory:nil];
	[objectImageViews removeAllObjects];
	CGSize thumbSize = (CGSize){75.0f, 75.0f};
	CGFloat x = 10.0f, y = 10.0f;
	for (NSString *fileName in fileNames) {
		if ([[fileName lastPathComponent]hasPrefix:@"object_"]) {
			SelectionImageView *imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
			UIImage *image = [UIImage imageWithContentsOfFile:fileName];
			imageView.image = image;
			imageView.imagePath = fileName;
			[[LoadedImages sharedLoadedImages].images setObject:image forKey:fileName];
			x += thumbSize.width + 5;
			[objectImageViews addObject:imageView];
		}
	}
}

- (void)makeBackgroundSelectArray {
	NSArray *fileNames = [[NSBundle mainBundle] pathsForResourcesOfType:nil inDirectory:nil];
	[backgroundImageViews removeAllObjects];
	CGSize thumbSize = (CGSize){75.0f, 75.0f};
	CGFloat x = 10.0f, y = 10.0f;
    
	for (NSString *fileName in fileNames) {
		if ([[fileName lastPathComponent]hasPrefix:@"background_"]) {
			SelectionImageView *imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
			UIImage *image = [UIImage imageWithContentsOfFile:fileName];
			[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
			[imageView.layer setBorderWidth: 2.0];
			imageView.image = image;
			imageView.imagePath = fileName;
			[[LoadedImages sharedLoadedImages].images setObject:image forKey:fileName];
            if (![[LoadedImages sharedLoadedImages].imageLayers objectForKey:fileName]) {
                UIGraphicsBeginImageContext(thumbSize);
                CGLayerRef imageLayer = CGLayerCreateWithContext(UIGraphicsGetCurrentContext(), image.size, NULL);
                UIGraphicsEndImageContext();
                UIGraphicsPushContext(CGLayerGetContext(imageLayer));
                [image drawInRect:(CGRect){(CGPoint){0, 0}, image.size}];
                UIGraphicsPopContext();
                [[LoadedImages sharedLoadedImages].imageLayers setObject:(NSObject *)imageLayer forKey:fileName];
                CFRelease(imageLayer);
            }
			x += thumbSize.width + 5;
			[backgroundImageViews addObject:imageView];
		}
	}
}

- (void)makeAllBackgroundSelectArray {
	NSArray *fileNames = [[NSBundle mainBundle] pathsForResourcesOfType:nil inDirectory:nil];
	[mainBackgroundViews removeAllObjects];
	CGSize thumbSize = (CGSize){75.0f, 75.0f};
	CGFloat x = 10.0f, y = 10.0f;
	for (NSString *fileName in fileNames) {
		if ([[fileName lastPathComponent]hasPrefix:@"background_"]) {
			SelectionImageView *imageView = [[SelectionImageView alloc] initWithFrame:(CGRect){x, y, thumbSize}];
			UIImage *image = [UIImage imageWithContentsOfFile:fileName];
			[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
			[imageView.layer setBorderWidth: 2.0];
			imageView.image = image;
			imageView.imagePath = fileName;
			[[LoadedImages sharedLoadedImages].images setObject:image forKey:fileName];
            if (![[LoadedImages sharedLoadedImages].imageLayers objectForKey:fileName]) {
                UIGraphicsBeginImageContext(thumbSize);
                CGLayerRef imageLayer = CGLayerCreateWithContext(UIGraphicsGetCurrentContext(), image.size, NULL);
                UIGraphicsEndImageContext();
                UIGraphicsPushContext(CGLayerGetContext(imageLayer));
                [image drawInRect:(CGRect){(CGPoint){0, 0}, image.size}];
                UIGraphicsPopContext();
                [[LoadedImages sharedLoadedImages].imageLayers setObject:(NSObject *)imageLayer forKey:fileName];
                CFRelease(imageLayer);
            }
			x += thumbSize.width + 5;
			[mainBackgroundViews addObject:imageView];
		}
	}
}

- (void)setUpSelectionScroller:(NSMutableArray *)elements {
    /*if (self.alpha != 1.0) {
        [self fade:self fromValue:self.alpha toValue:1.0 withDuration:0.25];
    }
    if (eraserButton.alpha == 1.0) {
        [self fade:eraserButton fromValue:1.0 toValue:0.4 withDuration:0.25];
    }*/
	currentImageViews = elements;
	int amountOfImages = [elements count];
	CGSize thumbSize = (CGSize){80.0f, 80.0f};
	self.contentSize = (CGSize){10 + amountOfImages * thumbSize.width + thumbSize.width / 3, thumbSize.height};
	self.tileSize = thumbSize;
	for (SelectionImageView *view in self.subviews) {
		[view removeFromSuperview];
	}
	for (SelectionImageView *imageView in elements) {
		[self addSubview:imageView];
	}
    if (currentImageViews == snapColorViews && lastSnapColorView == nil) {
        [((SelectionImageView *)[self.subviews objectAtIndex:0]).layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
        lastSnapColorView = ((SelectionImageView *)[self.subviews objectAtIndex:0]);
        [LoadedImages sharedLoadedImages].selectedSnapColor = ((SelectionImageView *)[self.subviews objectAtIndex:0]).imagePath;
    } 
    if (currentImageViews == backgroundImageViews && lastSelectedBackgroundView == nil) {
        [((SelectionImageView *)[self.subviews objectAtIndex:0]).layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
        lastSelectedBackgroundView = ((SelectionImageView *)[self.subviews objectAtIndex:0]);
        [LoadedImages sharedLoadedImages].selectedBackgroundImage = ((SelectionImageView *)[self.subviews objectAtIndex:0]).imagePath;
    } 
    if (currentImageViews == tokenImageViews && lastSelectedTokenView == nil) {
        [((SelectionImageView *)[self.subviews objectAtIndex:0]).layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
        lastSelectedTokenView = ((SelectionImageView *)[self.subviews objectAtIndex:0]);
          [LoadedImages sharedLoadedImages].selectedTokenImage = ((SelectionImageView *)[self.subviews objectAtIndex:0]).imagePath;
    } 
    if (currentImageViews == objectImageViews && lastSelectedObjectView == nil) {
        [((SelectionImageView *)[self.subviews objectAtIndex:0]).layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
        lastSelectedObjectView = ((SelectionImageView *)[self.subviews objectAtIndex:0]);
         [LoadedImages sharedLoadedImages].selectedObjectImage = ((SelectionImageView *)[self.subviews objectAtIndex:0]).imagePath;
    } 

}

- (void)fade:(UIView *)view fromValue:(float)fromValue toValue:(float)toValue withDuration:(float)duration {
    CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fade.duration = duration;		
    fade.fromValue = [NSNumber numberWithFloat:fromValue]; 
    fade.toValue = [NSNumber numberWithFloat:toValue];
    [view.layer addAnimation:fade forKey:@"fade"];
    if (toValue >= 1.0) {
        view.hidden = NO;
        view.alpha = 1.0;
    } else if (toValue <= 0.0) {
        view.hidden = YES;
        view.alpha = 0.0;
    } else {
        view.alpha = toValue;
    }
}

@end
